import paramiko
import os
from getpass import getpass


def deploy_application(host, username, password, local_path, remote_path):
    try:
        # 建立传输连接
        transport = paramiko.Transport((host, 22))
        transport.connect(username=username, password=password)

        # 创建 SFTP 客户端
        sftp = paramiko.SFTPClient.from_transport(transport)

        # 上传文件
        print(f"上传 {local_path} 到 {host}:{remote_path}")
        sftp.put(local_path, remote_path)

        # 创建 SSH 客户端执行命令
        client = paramiko.SSHClient()
        client._transport = transport

        # 停止服务
        print("停止应用服务...")
        stdin, stdout, stderr = client.exec_command('systemctl stop myapp.service')
        if stderr.read():
            print("停止服务时出错")

        # 备份旧版本
        print("备份旧版本...")
        stdin, stdout, stderr = client.exec_command(f'cp {remote_path} {remote_path}.bak')
        if stderr.read():
            print("备份时出错")

        # 设置权限
        print("设置文件权限...")
        stdin, stdout, stderr = client.exec_command(f'chmod 755 {remote_path}')
        if stderr.read():
            print("设置权限时出错")

        # 启动服务
        print("启动应用服务...")
        stdin, stdout, stderr = client.exec_command('systemctl start myapp.service')
        if stderr.read():
            print("启动服务时出错")

        # 验证状态
        print("验证服务状态...")
        stdin, stdout, stderr = client.exec_command('systemctl status myapp.service')
        status = stdout.read().decode()
        print(status)

        print("\n部署成功完成!")

    except Exception as e:
        print(f"部署失败: {str(e)}")
    finally:
        if 'sftp' in locals():
            sftp.close()
        if 'transport' in locals():
            transport.close()


if __name__ == '__main__':
    host = input("目标主机: ")
    username = input("SSH 用户名: ")
    password = getpass("SSH 密码: ")
    local_file = input("本地应用路径: ")
    remote_file = input("远程部署路径: ")

    deploy_application(host, username, password, local_file, remote_file)